import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw,
} from "vue-router";
import layout from "@/layout/layout.vue";
import type { AppRouteType } from "./type";
import { getToken } from "@/utils/token";

// / import.meta.glob() 直接引入所有的模块 Vite 独有的功能
const modules = import.meta.glob("./modules/**/*.ts", { eager: true });

const routeModuleList: AppRouteType[] = [];
const dataViewModuleList: AppRouteType[] = [];

// 加入到路由集合中
Object.keys(modules).forEach((key) => {
  const mod = (modules as any)[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  if (key !== "./modules/dataView.ts") {
    routeModuleList.push(...modList);
  } else {
    dataViewModuleList.push(...modList);
  }
});

const LoginRoute: AppRouteType = {
  path: "/login",
  name: "Login",
  component: () => import("@/views/login/index.vue"),
  meta: {
    title: "登录",
  },
};

const NotFoundRoute: AppRouteType = {
  path: "/:pathMatch(.*)*",
  name: "NotFound",
  component: () => import("@/views/errorPage/index.vue"),
  meta: {
    title: "404未找到",
  },
};

//路由表
export const routeList = [
  {
    path: "/",
    redirect: "/default",
    component: layout,
    children: [...routeModuleList, NotFoundRoute],
  },
  ...dataViewModuleList,
  LoginRoute,
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routeList as unknown as readonly RouteRecordRaw[],
});

//路由前置守卫，必须登录才能访问,否则跳转到登录页
router.beforeEach((to, from, next) => {
  // 判断目标路由是否存在
  const exists = router.getRoutes().some((route) => route.path === to.path);
  const siteName = "豌豆一点都不老";
  const pageTitle = to.meta.title;
  if (pageTitle) {
    document.title = `${pageTitle} - ${siteName}`;
  } else {
    document.title = siteName;
  }

  if (!exists) {
    // 如果目标路由不存在，跳转到404页面
    next({ name: "NotFound" }); // 假设404页面的路由名称为 'NotFound'
  } else if (to.meta.needAuth && !getToken()) {
    next({ name: "Login" }); // 假设登录页的路由名称为 'Login'
  } else {
    // 如果目标路由存在，继续导航
    next();
  }
});

export default router;
